import { type QueryKey } from '@tanstack/query-core';
import { type ChangeEvent, type FormEvent, useState } from 'react';
import useToast from '@/hooks/useToast';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { createPostHistory } from '@/services/api';

export type TCreateHistoryTranslatedField =
  | 'namePlaceholder'
  | 'save'
  | 'saveCompleted';

export default function CreateHistory({
  queryKey,
  id,
  translatedFields = {
    namePlaceholder: '请输入版块名称',
    save: '保存',
    saveCompleted: '保存完成',
  },
}: {
  queryKey: QueryKey;
  id: number;
  translatedFields?: Record<TCreateHistoryTranslatedField, any>;
}) {
  const [form, setForm] = useState({
    name: '',
  });
  const { show } = useToast();
  const queryClient = useQueryClient();

  const createPostHistoryMutation = useMutation(createPostHistory);

  async function onClickSave(e: FormEvent<HTMLFormElement>) {
    try {
      e.preventDefault();
      e.stopPropagation();

      const overview = '';
      const newContext = '';

      if (!newContext) {
        return;
      }

      await createPostHistoryMutation.mutateAsync({
        id,
        data: {
          name: form.name,
          overview,
          content: newContext,
        },
      });

      await queryClient.refetchQueries({ queryKey }, { throwOnError: true });
      show({
        type: 'SUCCESS',
        message: translatedFields.saveCompleted,
      });
    } catch (e) {
      createPostHistoryMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    }
  }

  function onChange(e: ChangeEvent<HTMLInputElement>) {
    const name = e.target.name;
    const value = e.target.value;
    setForm({ ...form, [name]: value });
  }

  return (
    <form onSubmit={onClickSave} className="vstack gap-4">
      <input
        name="name"
        type="text"
        className="form-control"
        value={form.name}
        onChange={onChange}
        placeholder={translatedFields.namePlaceholder}
      />

      <button
        type="submit"
        className="btn btn-primary col-6 col-lg-2 text-truncate text-nowrap"
        disabled={createPostHistoryMutation.isLoading}
      >
        {createPostHistoryMutation.isLoading && (
          <span
            className="spinner-border spinner-border-sm me-2"
            role="status"
            aria-hidden="true"
          ></span>
        )}
        {translatedFields.save}
      </button>
    </form>
  );
}
